<?php session_start(); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<?php
if (isset($_SESSION['lang']))
    require_once "./language_files/reviewOptions_" . $_SESSION['lang'] . ".php";
else
    require_once "./language_files/reviewOptions_en.php";
?>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
    <head>
        <meta http-equiv="X-UA-Compatible" content="IE=9" />
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
        <link href="jquery-ui-all.css" rel="stylesheet" type="text/css" />
        <link href="style3.css" rel="stylesheet" type="text/css" />
        <title></title>
        <?php include "jquery.php" ?>
        <script type="text/javascript" src="jquery-ui-1.8.21.custom.min.js"></script>
        <script type="text/javascript" src="functions.js"></script>
        <script type="text/javascript">
            //change the taxt in the label to view errors or success massages
            function success(text) {
                document.getElementById("label2").style.color = "green";
                document.getElementById("label2").innerHTML= text;
            }
            function error(text) {
                document.getElementById("label2").style.color = "red";
                document.getElementById("label2").innerHTML= text;
            }
            function ChangeTextCrit(text) {
                document.getElementById("label3").style.color = "red";
                document.getElementById("label3").innerHTML= text;
            }
            function ChangeTextCrit2(text) {
                document.getElementById("label3").style.color = "green";
                document.getElementById("label3").innerHTML= text;
            }
            //Author: Aya El Mobayad
            //a javascript function is created taking as a parameter the checked status
            //of the checkbox.
            function viewCustomFields(status){
                //If a status is true, It is assigned its inverse value which is false.
                status=!status;
                //The textboxes on the page are called and their disabled attribute is set
                //to the boolean value of the status variable. If the status is false,the boxes
                //are disabled, if true, they are enabled.
                document.form.Cname.disabled = status;
                document.form.Cdesc.disabled = status;
                //If the boxes are disabled, the span color will remain grey
                if (status == true){
                    document.getElementById('cust').style.color = 'grey';
                }
                //if the boxes are enabled, the span color will change to black.
                else {
                    document.getElementById('cust').style.color = 'black';
                }

            }
            //a function isAlphabet is created taking as a parameter the element
            //doing the action
            function isAlphabet(elem){
                //a variable is initialized that stores a regular expression for letters and underscores.
                var alphaExp = /^[A-Za-z _]*[A-Za-z][A-Za-z _]*$/;
                //The condition checks that the value of the element matches the reg-ex
                if(elem.value.match(alphaExp)){
                    // in the case it does, the function returns true.
                    return true;
                } else{
                    //if it doesnt, an alert message is displayed and the
                    //function returns false.
                    alert("please enter text only");
                    return false;
                }

            }
            $(document).ready(function(){
                check_top();
                $(document).find(":submit").click(function(){

                    $(document).find("form").attr("action", "reviewOptions.php?type=1");
                });
            });
        </script>
        <script type="text/javascript">
            $(function() {
                $( "#txtDate" ).datepicker({ dateFormat: "yy-mm-dd" });
            });
            $(function() {
                $( "#startDate" ).datepicker({ dateFormat: "yy-mm-dd" });
            });
        </script>
    </head>
    <!--  The javascript function disabling textboxes is called on page load -->
    <body onload="javascript: viewCustomFields(false);">
        <?php
        //Author: Aya El Mobayad
        //includes the file functions.php in the page in order to access the standardized
        //functions and call them as needed
        require_once 'functions.php';

        //retrieves the conference id from the associative array using a get request
        if (isset($_GET['conference_id'])) {
            $confID = mysql_real_escape_string($_GET['conference_id']);
        } else {
            $confID = mysql_real_escape_string($_POST['confID']);
        }
        $conference_name = get_conference_name($confID);
        echo"
	</br><span class=breadcrumbs><a href='subscriberConferencePage.php?conference_id={$confID}'>" . $conference_name . "</a>" . " > " . $lang['review_options'] . "</span> </br>";

        //specifies the connection to the server, as well as the username and password, and opens it

        //The conference long name is retrieved by calling the get_conference_name function from
        //functions.php and passing it the conference id of the conference for which the name
        //is needed, as a parameter.
        $cName = get_conference_name($confID);
        $confName = formatText_safe($cName);

        //The name retrieved using the previous function is printed at the top of the page
        //in a heading element
        print "<h1>{$confName}</h1>";
        ?><fieldset><legend><?php echo $lang['rate']; ?></legend>
            <form name='form' method='post' action='<?php echo "reviewOptions.php?conference_id={$confID}" ?>'>
                <input name="confID" type="hidden" value="<?php echo $confID ?>"/> <?
        //a query that retrieves all the rating criteria from the rating_criteria table in
        //the database is executed and the results are stored in a variable. If the query
        //fails to execute an error message is returned
        $result = mysql_query("SELECT * FROM rating_criteria")
                or die(mysql_error());

        //a variable num, which stores the number of rows returned from the query is initialized
        $num = mysql_num_rows($result);

        //a condition is made to check the value of the num variable. If no rows were returned,
        //its value should be zero
        if ($num <= 0) {
            //If no rows are returned, a failure message is echoed
            echo '<p align="center">' . $lang['norate'] . '</p>';
        } else {
            //if at least one row was returned, the title is printed
            echo '<br/>';
            echo '<h2>' . $lang['select'] . '</h2>';
            echo '<br/>';
            echo '<br/>';

            //the query results stored in the $results variable are passed to a method that returns the fetched row in an associative array.
            //The returned array is assigned to a newly initialized variable.
            //The loop will be executed as long as there are rows returned from the query
            while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
                //A query is executed retrieving all the criteria which have been previously set for the conference
                $q = mysql_query("SELECT * FROM conference_rating_criteria cr INNER JOIN rating_criteria r
                            ON cr.Rate_id = r.rate_id
                            WHERE cr.Rate_id = {$row['rate_id']} AND cr.Conference_id = '$confID'");
                //if the query returns rows
                if (mysql_num_rows($q) > 0) {
                    //The checkbox list will be populated, checked by default
                    echo "<input type=\"checkbox\" name=\"crit[]\" checked=\"checked\" value=\"{$row['rate_id']}\"/> <label><b>{$row['criteria_type']}:</b> {$row['description']}</label><br/>";
                } else {
                    // the checkbox list will be populated, getting as a value the criterion id
                    //and displaying the criteria name beside it. Both values are retrieved from the
                    //associative array $row
                    echo "<input type=\"checkbox\" name=\"crit[]\" value=\"{$row['rate_id']}\"/><label><b>{$row['criteria_type']}:</b> {$row['description']}</label><br/>";
                }
            }
            //after all the criteria are displayed in the checkboxes, an additional checkbox "other" will be created
            //for custom criteria, with a javascript onclick function taking as a parameter its checked status
            //to view the input boxes for a custom criteria
            echo '<input type="checkbox" name="customCrit" onclick="viewCustomFields(this.checked)"/><label><b>' . $lang['other'] . '</b></label>';
            //a span is created on which the custom criteria textboxes are appended
            echo '&nbsp;<span id="cust" style="color:grey;">
                    ' . $lang['name'] . ' <input type="text" name="Cname" onblur="isAlphabet(this);"/>
                    ' . $lang['desc'] . ' <input type="text" name="Cdesc" onblur="isAlphabet(this);"/></span>
                    <br/><br/>';
            //The label is created to view success/failure messages
            echo '<label id="label3"></label>';
        }

        //condition checks if the submitCrit button was clicked
        if (isset($_GET['type'])) {
            //Author: Mohamed Tarek
            //condition check if the allow check box was clicked
            if ((isset($_POST['allow']))) {
                //a query is update in the view_reviews row in conference table.
                mysql_query("UPDATE conference SET view_review = 1 WHERE conference_id = '$confID' ") or die("error");

                //End Documentation
            }
            //condition checks if there were checkboxes checked in the checkbox list named crit
            else if (isset($_POST['crit'])) {
                //The query deletes all the existing criteria records for this conference as a preparation
                //for the newly selected ones
                mysql_query("DELETE FROM conference_rating_criteria WHERE Conference_id = '$confID'");
                //the values of all the checked checkboxes are stored in an array
                $aCrit = $_POST['crit'];
                //a variable is initialized to store the length of the array as an integer
                $n = count($aCrit);

                //loops on all the values in the array of checkbox values
                for ($i = 0; $i < $n; $i++) {
                    //retrieves the value in the array at position i and stores it in a variable
                    $rateid = mysql_escape_string($aCrit[$i]);
                    //executes a query to insert the values of the ids of the checked criteria into the
                    //table with the id of the conference
                    mysql_query("INSERT INTO conference_rating_criteria (Conference_id, Rate_id)
                        VALUES ('$confID', '$rateid')") or die("error");
                }
                echo '<script>'
                , 'ChangeTextCrit2("Your settings have been saved");'
                , '</script>';
            } else {
                echo '<script>'
                , 'ChangeTextCrit("you did not choose any criteria");'
                , '</script>';
            }
            //condition checks if the checkbox for custom criteria is checked
            if (isset($_POST['customCrit'])) {
                if (($_POST['Cname'] == "") || ($_POST['Cdesc'] == "") || (($_POST['Cname'] == "") && ($_POST['Cdesc'] == ""))) {
                    //Inline javascript calling the alert function to display an error message
                    echo '<script>'
                    , 'ChangeTextCrit("Please enter custom criteria or uncheck the box");'
                    , '</script>';
                } else {
                    //the custom criterion is inserted into the database, retrieving the input
                    //for the query from the dynamically generated textboxes "customName" and "customDesc"
                    $NAME = mysql_real_escape_string($_POST[Cname]);
                    $DESC = mysql_real_escape_string($_POST[Cdesc]);
                    mysql_query("INSERT INTO rating_criteria (criteria_type, description)
                            VALUES ('$NAME','$DESC')") or die(mysql_error());
                    //a variable is initialized to contain the id of the newly inserted
                    //criterion using the mysql_insert_id function
                    $cRateID = mysql_insert_id();
                    //a query is executed to insert the the rates that were selected along with the conference
                    //they were selected in, into the database
                    mysql_query("INSERT INTO conference_rating_criteria (Conference_id, Rate_id)
                            VALUES ('$confID', '$cRateID')") or die("error");

                    //Inline javascript calling the alert function to display a success message
                    echo '<script>'
                    , 'ChangeTextCrit2("Your custom settings have been saved");'
                    , '</script>';
                }
            }
        }
        $old_dates = mysql_query("SELECT rev_startDate, rev_endDate FROM conference
                        WHERE conference_id = {$confID}") or die(mysql_error());
        $rslt = mysql_fetch_assoc($old_dates);
        $old_startDate = $rslt['rev_startDate'];
        $old_endDate = $rslt['rev_endDate'];
        $today = date("Y-m-d");
        if ($today > $old_startDate) {
            echo "<script type='text/javascript'>
                                  $('#startDate').attr('disabled', 'true');
                                   $('#txtDate').attr('disabled', 'true');
                                   $('#DL').html('Review already started');
                                    $('#DL2').html('Review already started');
                                    $('#startDate').css('border-color', 'red');
                                     $('#txtDate').css('border-color', 'red');
                            </script>";
        }
        //closes connection to database

        //End Documentation
        ?>
                <fieldset>
                    <legend><?php echo $lang['review']; ?></legend>
                    <p><?php echo $lang['start']; ?>
                        <input size="26" type="text" name="StartDate" id="startDate"
                               value="<?php echo $old_startDate; ?>" readonly="readonly" style="cursor: text;"/><label style="color: red;"id="DL"></label>

                    </p>
                    <p><?php echo $lang['deadline']; ?>
                        &nbsp;<input size="26" type="text" name="txtDate" id="txtDate"
                                     value="<?php echo $old_endDate; ?>" readonly="readonly" style="cursor: text;"/><label id="DL2" style="color: red;"></label>
                        <br /> <label id="label2"></label>
                    </p>
                    <p>
                        <input type="checkbox" name="allow" />
                <?php echo $lang['allow']; ?>
                    </p>
                    <br />
                    <br />
                    <br />
                    <input type ="submit" id="submit" name="submitCrit" value="<?php echo $lang['submit']; ?>"/><br />
            </form>
        </fieldset>
        </fieldset>

<?php
if (isset($_POST['txtDate']) && isset($_POST['StartDate'])) { // checking if values passed
    $D1 = strtotime($_POST['txtDate']);
    $d = mysql_real_escape_string($D1);
    $newdate = date("Y-m-d", $d);
    $S1 = strtotime($_POST['StartDate']);
    $s = mysql_real_escape_string($S1);
    $startnewdate = date("Y-m-d", $s);
    $today = date("Y-m-d");
    if ($newdate < $today || $startnewdate < $today) {
        echo '<script type="text/javascript">'
        , 'error("Start/deadline dates can not be in the past");'
        , '</script>';
    } else if ($s > $d) {
        echo '<script type="text/javascript">'
        , 'error("start review date can not be before deadline date!");'
        , '</script>';
    } else if ($newdate != null && $startnewdate != null) {
        // checking if dates are > today and end > start

            //updating review deadline in the database
            mysql_select_db("mydb", $con);
            $query = "
                        UPDATE conference
                        SET rev_startDate = '{$startnewdate}', rev_endDate = '{$newdate}'
                        WHERE conference_id = {$confID}
                        ";
            echo '<script type="text/javascript">'
            , 'success("deadline set successfuly");'
            , '</script>';

            if (!mysql_query($query, $con)) {
                echo $lang['error_2'];
            }

    } else {
        echo '<script type="text/javascript">'
        , 'error("empty or invalid deadline");'
        , '</script>';
    }
}
?>
    </body>
</html>

